package org.jeecg.common.rc.aop.curl_aop;

import org.jeecg.common.util.JlStrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class CurlAop {

    @Autowired
    HttpServletRequest httpServletRequest;

    @Pointcut("execution(* org.jeecg..BaseController.*(..))")
    public void p1() {
    }

    @Pointcut("execution(* org.jeecg..*Api*+.*(..))")
    public void p2() {
    }

    @Pointcut("execution(* org.jeecg..*Controller*+.*(..))")
    public void p3() {
    }

    @Pointcut("p1() || p2() || p3()")
    public void logCurlMethods() {
    }

    @Pointcut("@annotation(org.jeecg.common.rc.aop.curl_aop.CurlLog)")
    public void logCurlAnnotation() {
    }

    @SneakyThrows
    @Around("logCurlMethods()")
    public Object logBefore(ProceedingJoinPoint pjp) {
        Object proceed;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            if (httpServletRequest != null) {
                String curlCommand = CurlUtil.generateCurlCommand(httpServletRequest, pjp);
                StringBuffer requestURL = httpServletRequest.getRequestURL();
                String restUrl = JlStrUtil.getRestUrl(String.valueOf(requestURL));
                log.error("See Error restUrl:{} ", restUrl);
//                String formattedCurlCommand = formatCurlCommand(curlCommand);
                log.error("See Error Curl Command:{} ", curlCommand);
            }
            throw e;
        }
        return proceed;
    }

    @Around("logCurlAnnotation()")
    public Object logWithAnnotation(ProceedingJoinPoint pjp) throws Throwable {
        if (httpServletRequest != null) {
            String curlCommand = CurlUtil.generateCurlCommand(httpServletRequest, pjp);
//            String formattedCurlCommand = formatCurlCommand(curlCommand);
            log.info("See Curl Command:{} ", curlCommand);
        }
        Object proceed = pjp.proceed();
        return proceed;
    }

    // Rest of the code remains the same...
}
